import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
// 这里名字字段是固定的，一定要和上下保持一致 而且不要自由发挥加个s去个s
const state = {
  token: getToken() || '',
  userInfo: {}
}
// mutations是唯一修改state的途径
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    // 设置了 token 的同时, 同步到本地cookies中
    setToken(newToken)
  },
  setUserInfo(state, newInfo) {
    state.userInfo = newInfo
  }
}
const actions = {
  login(context, data) {
    return new Promise((resolve, reject) => {
      // 发送登录请求, 异步操作
      reqLogin(data).then(res => {
        const newToken = res.data
        context.commit('setToken', newToken)
        // 成功resolve
        resolve(res)
      }).catch(error => {
        // 失败reject
        reject(error)
      })
    })
  },
  async getUserInfo({ commit }) {
    const { data: res2 } = await reqGetUserInfo()
    const { data: res1 } = await reqGetUserDetailById(res2.userId)
    const res3 = { ...res2, ...res1 }
    console.log('wondsf', res3)
    commit('setUserInfo', res3)
    return res3
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
